﻿using CommonDevelop;
using CommonDevelop.DB;
using CommonEngine;
using CommonFP;
using ManageDB;
using ManageDto;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ManageRepository
{
    /// <summary>
    /// 岗位数据层接口
    /// </summary>
    public interface IPositionRepository : IBase<Base_Position>
    {
        IEnumerable<Base_Position> GetPostByUserId(string UserId);
        int SavePost(string UserId, params Base_Position[] post);
    }

    /// <summary>
    /// 岗位数据层
    /// </summary>
    public class PositionRepository : DBBase<Base_Position>, IPositionRepository
    {
        public override Expression<Func<Base_Position, bool>> WhereKeyWord(string keyword)
            => t => t.ShortName.Contains(keyword)
            || t.FullName.Contains(keyword)
            || t.Nature.Contains(keyword);

        public IEnumerable<Base_Position> GetPostByUserId(string UserId)
        {
            if (UserId.IsEmpty())
                return Enumerable.Empty<Base_Position>();

            var db = SugarBizDB.GetReadOnlyInstance();
            //链表查询--用户关联的岗位
            List<Base_Position> result = db.Queryable<Base_User, Base_UserRelation, Base_Position>(
                (uu, ur, post)
                => new JoinQueryInfos(JoinType.Inner, uu.UserId == ur.UserId,
                JoinType.Inner, ur.RelObjectId == post.PositionId && ur.RelType == 2))
                .Where(uu => uu.UserId == UserId)
                .Select<Base_Position>((uu, ur, post) => post)
                .ToList();

            return result;
        }

        public int SavePost(string UserId, params Base_Position[] post)
        {
            if (UserId.IsEmpty() || post.IsNullOrEmpty())
                return 0;

            List<Base_UserRelation> dataLs = new List<Base_UserRelation>();
            post.ForEach(a =>
            {
                dataLs.Add(new Base_UserRelation { UserId = UserId, RelObjectId = a.PositionId, BusinessID = a.BusinessID, RelType = (int)RelType.Post });
            });

            var DB = SugarBizDB.GetInstance();
            int result = 0;
            try
            {
                DB.BeginTran();
                DB.Deleteable<Base_UserRelation>()
                    .Where(a => a.UserId == UserId)
                    .ExecuteCommand();

                //插入多条数据
                result = DB.Insertable<Base_UserRelation>(dataLs)
                    .InsertColumns(it => new { it.UserId, it.RelObjectId, it.BusinessID, it.RelType })
                    .ExecuteCommand();
                DB.CommitTran();
            }
            catch (Exception e)
            {
                DB.RollbackTran();
                throw e;
            }
            return result;
        }
    }
}
